package thinkinjava4.ch14_typeinfo;

import java.util.logging.XMLFormatter;

import static thinkinjava4.util.Print.print;

class Base {
}

class Derived extends Base {
}

public class FamilyVsExactType {
    private static void test(Object x) {
        // instanceof不能动态检查类型
        if (x instanceof Derived) {
            System.out.println(x.getClass().getSimpleName() + " instanceof Derived");
        } else if (x instanceof Base) {
            System.out.println(x.getClass().getSimpleName() + " instanceof Base");
        }
        //isInstance可以动态检查类型
        Class[] classes = {Derived.class, Base.class};
        for (Class aClass : classes) {
            if (aClass.isInstance(x)) {
                System.out.println(aClass.getSimpleName() + " isInstance(" + x.getClass().getSimpleName() + ")");
                break;
            }
        }
        System.out.println("---------------------------------------");
        print("Testing x of type " + x.getClass());
        print("x instanceof Base " + (x instanceof Base));
        print("x instanceof Derived " + (x instanceof Derived));
        print("Base.isInstance(x) " + Base.class.isInstance(x));
        print("Derived.isInstance(x) " + Derived.class.isInstance(x));
        print("x.getClass() == Base.class " + (x.getClass() == Base.class));
        print("x.getClass() == Derived.class " + (x.getClass() == Derived.class));
        print("x.getClass().equals(Base.class) " + (x.getClass().equals(Base.class)));
        print("x.getClass().equals(Derived.class) " + (x.getClass().equals(Derived.class)));
    }

    public static void main(String[] args) {
        test(new Base());
        System.out.println("--------------------------------");
        test(new Derived());
    }
}
